package ace.cmp.security.oauth2.authz.server.test.core.controller;

import ace.cmp.security.oauth2.authz.server.test.core.properties.Oauth2ServerTestProperties;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import lombok.AllArgsConstructor;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Caspar
 */
@AllArgsConstructor
@RestController
public class Oauth2ServerTestController {
  private final Oauth2ServerTestProperties properties;

  @RequestMapping("/oauth2/token")
  public Map<String, Object> token() {
    Map<String, Object> configResult =
        Optional.ofNullable(this.properties).map(p -> p.getMockToken()).orElse(null);
    if (configResult != null && configResult.size() > 0) {
      return configResult;
    }
    Map<String, Object> result = new HashMap<>();
    result.put("access_token", UUID.randomUUID().toString());
    result.put("expires_in", Duration.ofDays(5).toSeconds());
    result.put("refresh_token", UUID.randomUUID().toString());
    result.put("token_type", OAuth2AccessToken.TokenType.BEARER.getValue());
    result.put("scope", Arrays.asList("all"));
    result.put("id_token", UUID.randomUUID().toString());
    return result;
  }

  @RequestMapping("/oauth2/introspect")
  public Map<String, Object> introspect() {

    Map<String, Object> configResult =
        Optional.ofNullable(this.properties).map(p -> p.getMockIntrospect()).orElse(null);
    if (configResult != null && configResult.size() > 0) {
      return configResult;
    }
    Map<String, Object> result = new HashMap<>();
    result.put("active", true);
    result.put("sub", "default");
    result.put("aud", Arrays.asList("default"));
    result.put("nbf", LocalDateTime.now().plusDays(1).toInstant(ZoneOffset.UTC).getEpochSecond());
    result.put("scope", "all");
    result.put("iss", "http://localhost:8080");
    result.put("exp", LocalDateTime.now().plusDays(1).toInstant(ZoneOffset.UTC).getEpochSecond());
    result.put("jti", UUID.randomUUID().toString());
    result.put("client_id", "default");
    result.put("token_type", OAuth2AccessToken.TokenType.BEARER.getValue());
    return result;
  }
}
